﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eStore.Models;
using eStore.ViewModels;

namespace eStore.Controllers
{
    public class StoreController : Controller
    {
        private ICategoryRepository _categoryRepo;
        private IProductRepository _productRepo;
        private IUserRepository _userRepo;

        public StoreController():this(new CategoryRepository(),new ProductRepository(),new UserRepository()) { 
        
        }

        public StoreController(ICategoryRepository categoryRepo, IProductRepository productRepo, IUserRepository userRepo)
        {
            _categoryRepo = categoryRepo;
            _productRepo = productRepo;
            _userRepo = userRepo;
        }

        //
        // GET: /Store/
        public ActionResult Index()
        {
            var products = _productRepo.GetAll();
            var storeIndexViewModel = new StoreIndexViewModel() { PageTitle = "eStore - All Products", AllProducts = products.ToList() };
            return View(storeIndexViewModel);
        }

        [HandleError(View="Error")]
        public ActionResult Browse(String categoryname)
        {
            if (String.IsNullOrEmpty(categoryname))
                throw new Exception("Category Name is required!");

            var allMatchedProducts = _categoryRepo.GetByCategoryName(categoryname).Products;
            StoreBrowseViewModel oViewModel = new StoreBrowseViewModel() { PageTitle = String.Format("Browsing {0} department", categoryname), StoreBrowseProducts = allMatchedProducts };

            return View(oViewModel);
        }

        public ActionResult Details(int? id)
        { 
            int iProductId = id ?? id.Value;

            var product = _productRepo.GetById(iProductId);
            StoreDetailsViewModel oViewModel = new StoreDetailsViewModel() { PageTitle = String.Format("Detail for {0}", product.ProductName), SelectedProduct = product, NewReview = new ProductReview() { ProductProductId = product.ProductId } };
            return View(oViewModel);
        }


        [Authorize]
        [HttpPost]
        public ActionResult Details(int? id,ProductReview NewReview)
        {
            if (ModelState.IsValid)
            {
                var userId = System.Threading.Thread.CurrentPrincipal.Identity.Name;
                var foundUser = _userRepo.GetUserByName(userId);
                if (foundUser != null)
                    NewReview.UserUserId = foundUser.UserId;
                NewReview.CreatedDate = DateTime.Now;
                _userRepo.SubmitReview(NewReview);
                NewReview.UserUserId = 0;
                NewReview.StarRate = 0;
                NewReview.ReviewComment = "";
            }
            
            var product = _productRepo.GetById(NewReview.ProductProductId);
            StoreDetailsViewModel oViewModel = new StoreDetailsViewModel() { PageTitle = String.Format("Detail for {0}", product.ProductName), SelectedProduct = product, NewReview = NewReview };
            return View(oViewModel);
        }

        //[HttpPost]
        //public ActionResult Review(FormCollection formValues)
        //{

        //    return View();
        //}

        [HttpPost]
        public ActionResult Review(ProductReview NewReview)
        {
            try
            {
                if (!(ModelState.IsValid))
                    return RedirectToAction("Details", "Store", new { @id = NewReview.ProductProductId, NewReview = NewReview });
                    
            }
            catch {
                return RedirectToAction("Details", "Store", new { @id = NewReview.ProductProductId, NewReview = NewReview });
            }
            return View();
        }

        [ChildActionOnly]
        public ActionResult Categories() {
            var allCategories = _categoryRepo.GetAll();

            return View(allCategories);
        }

        [ChildActionOnly]
        public ActionResult Search()
        {
            SearchModel oSearchModel = new SearchModel();

            return View(oSearchModel);
        }

        [HttpPost]
        public ActionResult SearchStore(SearchModel searchModel)
        {
            String sSearchTerm = searchModel.SearchItem;
            var allMatchedProducts = _productRepo.FindProductByTextWildCard(sSearchTerm);

            
            StoreSearchStoreViewModel oViewModel = new StoreSearchStoreViewModel() { PageTitle = string.Format("Search Result for {0}", sSearchTerm), ProductSearchResults = allMatchedProducts };

            return View(oViewModel);
            
        }

        [HttpGet]
        public JsonResult SearchAutoComplete()
        {
            string sTerm = Request.QueryString["term"];
            var allMatchedProducts = _productRepo.FindProductByTextWildCard(sTerm);
            var jsonRslt = allMatchedProducts.ToList().ConvertAll((x)=>{
                return new { @value = x.ProductId.ToString(), @label = x.ProductName };
            });

            return Json(jsonRslt, JsonRequestBehavior.AllowGet);
        }


    }
}
